package com.lkd.http.controller;

import com.lkd.common.VMSystem;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.ConvertUtils;
import com.lkd.vo.PayVO;
import com.lkd.wxpay.WXConfig;
import com.lkd.wxpay.WxPayDTO;
import com.lkd.wxpay.WxPaySDKUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private WxPaySDKUtil wxPaySDKUtil;

    /**
     * 创建小程序订单支付
     *
     * @param payVO
     * @return
     */
    @PostMapping("/weixinPay")
    public String weixinPay(@RequestBody PayVO payVO) {
        //创建订单
        var orderEntity = orderService.createOrder(payVO);
        //封装支付请求对象调用支付
        var wxPayDTO = new WxPayDTO();
        wxPayDTO.setBody(orderEntity.getSkuName());
        wxPayDTO.setOpenid(orderEntity.getOpenId());
        wxPayDTO.setOutTradeNo(orderEntity.getOrderNo());
        wxPayDTO.setTotalFee(orderEntity.getAmount().intValue());

        //调用微信支付并返回结果
        return wxPaySDKUtil.requestPay(wxPayDTO);
    }

    @RequestMapping("/payNotify")
    @ResponseBody
    public void payNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("调用了回调方法");
        try {
            //输入流转换为xml字符串
            //String notifyResult = ConvertUtils.convertToString(request.getInputStream());
            String orderSn = "BGUAP7iu348826491769900";//wxPaySDKUtil.validPay(notifyResult);
            if (orderSn != null) {
                OrderEntity orderEntity = orderService.getByOrderNo(orderSn);
                if (orderEntity != null) {
                    orderEntity.setStatus(VMSystem.ORDER_STATUS_PAYED);
                    orderEntity.setPayStatus(VMSystem.PAY_STATUS_PAYED);
                    orderService.updateById(orderEntity);   //保存

                    //在orderService调用发货方法,实现发货
                    orderService.vendOut(orderSn,orderEntity.getSkuId(),orderEntity.getInnerCode());
                    //给微信支付一个成功的响应
                    response.setContentType("text/xml");
                    response.getWriter().write(WXConfig.RESULT);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("支付回调处理失败", e);
        }
    }
}
